package org.zfm.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.zfm.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override //前置拦截 调用controller方法之前调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(requestURL);
        if(requestURL.toString().contains("swagger")){
            return true;
        }

        // 判断是否有登录信息--从请求头中获取登录信息
        String token = request.getHeader("token");
        if(StringUtils.isNotBlank(token)){
            // 从redis中根据token获取登录信息，判断登录是否过期
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            if(Objects.nonNull(logininfo)){
                //如果登陆了，就刷新登录过期时间
                redisTemplate.opsForValue().set(token,logininfo);
                return true;
            }
        }
        // 登录失败 返回提示信息
        // 权限拦截 //@TODO
        // 返回未登录的提示信息 提示前端未登录
        // 设置响应请求的字符编码集
        response.setCharacterEncoding("utf-8");
        // 设置响应体的类型
        response.setContentType("application/json; charset=UTF-8");
        // 获取响应打印流
        PrintWriter writer = response.getWriter();
        // 拼接将要返回前端的json字符串
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        // 关闭输出流
        writer.close();
        return false;
    }

    @Override // 后置拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override // 最终执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
